import { Component, OnInit, ViewChild } from '@angular/core';
import { NzDatePickerComponent } from 'ng-zorro-antd/date-picker';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { defalutImg } from 'src/app/comm';
import { Router, ActivatedRoute } from '@angular/router';

import { CommonService } from '../../../../services-common/common.service';
import { SellLuckdrawManageService } from '../sell-luckdraw-manage.service';

@Component({
  selector: 'app-order-lottery-config',
  templateUrl: './order-lottery-config.component.html',
  styleUrls: ['./order-lottery-config.component.scss'],
  providers: [DatePipe]
})
export class OrderLotteryConfigComponent implements OnInit {
  @ViewChild('endDatePicker') endDatePicker!: NzDatePickerComponent;

  isSpinning: boolean = false;
  routerParams: any = {};

  formParams: any = {
    status: 0,
    userType: '', // 0-通用 1-C端 2-B端
    activityName: '', // 活动名
    beginTime: '',
    endTime: '',
    orderPrice: '', // 订单门槛
    bak: '' // 备注
  };

  userTypeOptions: any = [
    { label: 'B端用户', value: '2', checked: false },
    { label: 'C端用户', value: '1', checked: false }
  ];

  /**************************************** 时间段选择 START ************************************** */
  disabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.formParams.endTime) {
      return false;
    }
    return startValue.getTime() > new Date(this.formParams.endTime).getTime();
  };

  disabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.formParams.beginTime) {
      return false;
    }
    return endValue.getTime() <= new Date(this.formParams.beginTime).getTime();
  };
  /**************************************** 时间段选择 END **************************************** */

  tipStr: string = '如果两个时间都为空的话，则该配置会一直被随机到。如果某个时间为空的话，则只会用另一个时间来判断状态变化。';

  // type：奖品类型; couponNo：奖品ID; probability：概率; withdraw：0-退单撤回 1-不撤回; stock：发放总量(库存)
  tableData: any = [
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 0, loading: false},
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 1, loading: false},
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 2, loading: false},
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 3, loading: false},
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 4, loading: false},
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 5, loading: false},
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 6, loading: false},
    {name: '', imgUrl: '', type: '', couponNo: '', probability: '', minProbability: '', maxProbability: '', withdraw: '1', stock: '', isChecked: false, sort: 7, loading: false},
  ];
  subloading: boolean = false;
  fallback: string = defalutImg;

  constructor(
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private services: SellLuckdrawManageService
  ) { 
    this.activatedRoute.queryParams.subscribe((res: any) => {
      this.routerParams = res || {};
    })
  }

  ngOnInit(): void {
    if (this.routerParams.type == 1 || this.routerParams.type == 2) {
      this.getDetailData();
    }
  }

  // 查询详情
  async getDetailData() {
    try {
      this.isSpinning = true;
      const res: any = await this.services.queryLotteryDetail({ id: this.routerParams.id });
      this.isSpinning = false;
      
      if (res.code == 0) {
        const { activity, list } = res.data || {};

        this.formParams.status = activity.status;
        this.formParams.userType = activity.userType;

        if (activity.userType) {
          this.userTypeOptions.forEach((ele: any) => {
            if (activity.userType == '0') {
              ele.checked = true;
            } else {
              if (String(activity.userType).indexOf(ele.value) != -1) {
                ele.checked = true;
              }
            }
          });
        }

        this.formParams.activityName = activity.activityName;
        this.formParams.beginTime = activity.beginTime;
        this.formParams.endTime = activity.endTime;
        this.formParams.orderPrice = activity.orderPrice;
        this.formParams.bak = activity.bak;

        if (list.length) {
          list.forEach((ele: any) => {
            ele.isChecked = ele.withdraw == 0 ? true : false;
            ele.loading = false;
          });
        }
        this.tableData = list || [];
      }
    } catch (error: any) {
      this.isSpinning = false;
      this.message.error(error);
    }
  }

  // 适用用户change
  logChange(value: object[]): void {
    let tempArr: any[] = value.map((item: any) => {
      if (item.checked) {
        return item.value
      }
    }).filter(tag => tag);

    if (tempArr.length == 2) {
      this.formParams.userType = '0';
    } else {
      this.formParams.userType = tempArr.join(',');
    }
  }

  // 有效时间
  handleStartOpenChange(open: boolean): void {
    if (!open) {
      this.endDatePicker.open();
    }
  }
  // handleEndOpenChange(open: boolean): void {
  //   console.log('handleEndOpenChange', open);
  // }

  // 清除Item
  clearItem(item: any, index: number) {
    this.tableData[index].name = '';
    this.tableData[index].imgUrl = '';
    this.tableData[index].type = '';
    this.tableData[index].couponNo = '';
    this.tableData[index].probability = '';
    this.tableData[index].withdraw = '1';
    this.tableData[index].isChecked = false;
    this.tableData[index].stock = '';
  }

  // 拖拽排序
  drop(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this.tableData, event.previousIndex, event.currentIndex);
  }

  /**
   * 类型选择
   * @param value 1-占位 2-优惠券 3-谢谢惠顾
   */
  typeChange(value: any, index: number) {
    if (value == 3) {
      this.tableData[index].name = '谢谢参与';
      this.tableData[index].couponNo = '';
      this.tableData[index].isChecked = false;
    }
    if (value == 1 || value == 7 || value == 8) {
      this.tableData[index].stock = '0';
      this.tableData[index].probability = '0';
      this.tableData[index].minProbability = '0';
      this.tableData[index].maxProbability = '0';
      this.tableData[index].isChecked = false;
    }
    if (value == 6) {
      this.tableData[index].couponNo = '';
      this.tableData[index].isChecked = false;
    }
  }

  // upload img
  onModalPreview(ev: any, index: number) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj, index);
  }
  // uploadInterface
  async uploadInterface(file: any, index: number) {
    if (!file || this.tableData[index].loading) {
      return
    }

    try {
      this.tableData[index].loading = true;
      const res: any = await this.services.uploadFileData(file)
      this.tableData[index].loading = false;

      if (res.code == 0) {
        this.message.success('图片上传成功');
        this.tableData[index].imgUrl = res.data || '';
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.tableData[index].loading = false;
      this.message.error(error);
    }
  }

  // 删除图片
  deleteImg(index: number) {
    this.tableData[index].imgUrl = '';
  }

  // 提交保存
  async subForm() {
    if (!this.verifData()) {
      return
    }

    let subArray = JSON.parse(JSON.stringify(this.tableData))
    subArray.map((item: any, index: number) => {
      item.withdraw = item.isChecked ? 0 : 1;
      item.sort = index;
      delete item.isChecked;
      delete item.loading;
      
      // 复制新增: 删除id
      if (this.routerParams.type == 2) {
        delete item.id;
      }
      return {
        ...item
      }
    })

    this.formParams.beginTime = this.formParams.beginTime ? this.datePipe.transform(this.formParams.beginTime, 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams.endTime = this.formParams.endTime ? this.datePipe.transform(this.formParams.endTime, 'yyyy-MM-dd HH:mm:ss') : '';
    let params: any = {
      activity: this.formParams,
      activityPrizeList: subArray
    }

    let result: any;
    this.subloading = true;
    if (this.routerParams.type == 0 || this.routerParams.type == 2) {
      // console.log('新增', params);
      delete params.activity.id;
      params.activity.status = 0;
      result = await this.services.addLotteryItem(params);
    } else if (this.routerParams.type == 1) {
      // console.log('编辑', params);
      params.activity.id = this.routerParams.id;
      result = await this.services.updateLotteryItem(params);
    }

    this.subloading = false;
    if (result.code == 0) {
      this.message.success('保存成功');
      history.back();
    } else {
      this.message.error(result.message || '保存失败');
    }
  }
  
  back() {
    history.back();
  }

  // 验证
  verifData() {
    // 图片
    let tempImgUrl = this.tableData.some((item: any) => {
      return item.type != 3 && !item.imgUrl;
    });
    // 图片
    let tempType = this.tableData.some((item: any) => {
      return item.type == 3;
    });
    // 奖品ID
    let tempCouponNo = this.tableData.some((item: any) => {
      return [2, 7, 8].includes(item.type) && !item.couponNo;
    });
    // 发放量
    let tempStock = this.tableData.some((item: any) => {
      // typeof item.stock
      return [2, 7, 8].includes(item.type) && this.commonService.isEmpty(item.stock);
    });

    if (!this.formParams.userType) {
      this.message.warning('请选择适用用户');
      return false;
    } else if (!this.formParams.activityName) {
      this.message.warning('请输入活动名称');
      return false;
    } else if (!String(this.formParams.orderPrice)) {
      this.message.warning('请输入订单门槛');
      return false;
    } else if (this.verifTable('name')) {
      this.message.warning('奖品配置：名称存在未填写项');
      return false;
    } else if (tempImgUrl) {
      this.message.warning('奖品配置：图标存在未上传项');
      return false;
    } else if (this.verifTable('type')) {
      this.message.warning('奖品配置：选择类型存在未选项');
      return false;
    } else if (!tempType) {
      this.message.warning('奖品配置：至少选择一个谢谢参与类型');
      return false;
    } else if (tempCouponNo) {
      this.message.warning('奖品配置：奖品ID存在未填写项');
      return false;
    } else if (this.verifTable('minProbability')) {
      this.message.warning('奖品配置：概率最小值存在未填项');
      return false;
    } else if (this.verifTable('maxProbability')) {
      this.message.warning('奖品配置：概率最大值存在未填项');
      return false;
    } else if (tempStock) {
      this.message.warning('奖品配置：发放总量存在未填写项');
      return false;
    } else {
      return true;
    }
    // else if (this.verifTable('probability')) {
    //   this.message.warning('奖品配置：概率存在未填写项');
    //   return false;
    // } else if (this.getProbabilityTotal() != 10000) {
    //   this.message.warning('奖品配置：概率总和需等于10000');
    //   return false;
    // }
  }

  // 验证table项指定项值是否包含空
  verifTable(verifField: string) {
    return this.tableData.some((item: any) => {
      return item[verifField] === '' || item[verifField] === undefined || item[verifField] === null;
    });
  }

  // 概率总和
  getProbabilityTotal() {
    return this.tableData.reduce((total: any, item: any) => {
      return total + (Number(item.probability) || 0)
    }, 0)
  }
}
